Learning Flex Basics (Part 2): Creating a Simple Calculator with Macromedia Flex
Table of Contents
- Introduction
- Building the Calculator
- Create the Application Object
- Add a Panel for the Calculator
- Add the Calculator Display
- Add a Grid to Lay Out the Buttons
- Add the Calculator Buttons
- Create the CalculatorController Class
- Add Properties to the Controller Class
- Add Controller Methods
- Instantiate the CalculatorController Class
- Complete Code Listing for calculator.mxml
- Complete Code Listing for CalculatorController.as
- Where to Go From Here
Create the CalculatorController Class
Create an ActionScript class that will be a controller for the calculator. Because the application is simple, you will include the data model in the controller rather than create it separately.
Creating a class in ActionScript is simple and is similar to the way you create one in other object-oriented languages. The basic syntax is:
class ClassName
{
[properties and methods]
}
Save classes as .as files; the file name must be the same as the class name.
Although the compiler will generate an empty constructor if the class definition
does not contain one, it is good practice to include a constructor, even if
it does nothing. Constructor methods in ActionScript may not take parameters
or return any values, and constructor overloading is not supported. Constructors,
like other methods, are created using the function keyword:
[public|private] function ClassName(){}
Methods (and properties) are public by default, meaning that they can be accessed from outside the class. It's good practice to always make them public or private explicitly as a reminder to make them private if they don't need to be public.
- Open a new empty file and save it as CalculatorController.as in the same directory as your calculator.mxml file.
-
Add a class definition for the CalculatorController class:
class CalculatorController {} -
Add an empty constructor function inside the class block:
public function CalculatorController(){}